<?php
/**
 * 支付回调
 * User: peter
 * Date: 2018/7/2
 * Time: 下午5:12
 */

namespace app\mall\controller;


use app\model\OrderProcess;
use app\model\UpgradeAgentOrder;
use app\mall\logic\Distribution;
use Naixiaoxin\ThinkWechat\Facade;
use think\facade\Log;

class PayNotify extends Base
{


    /**
     * @purpose 微信支付升级代理商异步回调
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function wechatUpgradeAgentAsync ()
    {

        $app        = Facade::payment('official_account');
        $response   = $app->handlePaidNotify(function($message, $fail) {
            $return_code    = strtolower($message['return_code']);
            $result_code    = strtolower($message['result_code']);
            if (
                $return_code === 'success' &&
                $result_code === 'success'
            ) {
                $order          = new UpgradeAgentOrder();
                $member         = new \app\model\Member();
                $member->startTrans();
                $uuid       = $message['attach'];
                $member_info     = $member
                    ->where('uuid', $uuid)
                    ->field('uid,agent_end_time,agent')
                    ->find();
                if (!$member_info) {
                    $order->rollback();
                    return $fail('Member not exists!');
                }
                $order_info     = $order
                    ->where([
                        'order_no'   => $message['out_trade_no'],
                        'uid'           => $member_info->uid
                    ])
                    ->lock(true)
                    ->field('id,uid,order_no,is_pay')
                    ->find();
                if (!$order_info) {
                    $member->rollback();
                    return $fail['Order is not find!'];
                }
                if ($order_info->is_pay === 2) {
                    $member->commit();
                    return true;
                }
                // 更新用户数据
                $agent_end_time = 0;
                if ($member_info->agent_end_time === 0) {
                    $agent_end_time = strtotime(date('Y-m-d',time() + (3600 * 24 * 3365)).' 00:00:00');
                } else {
                    $agent_end_time = strtotime(date('Y-m-d',$member_info->agent_end_time + (3600 * 24 * 365)).' 00:00:00');
                }
                // 如果代理商已经到期则重新计算时间
                if ($member_info->agent === 1) {
                    $agent_end_time = strtotime(date('Y-m-d',time() + (3600 * 24 * 365)).' 00:00:00');
                } else {
                    $agent_end_time = strtotime(date('Y-m-d',$member_info->agent_end_time + (3600 * 24 * 365)).' 00:00:00');
                }
                $member_result  = $member
                    ->save([
                        'agent' => 2,
                        'agent_end_time' => $agent_end_time
                    ], ['uid' => $member->uid]);
                // 更新订单状态
                $start_time = $member_info->agent_end_time ? $member_info->agent_end_time : strtotime(date('Y-m-d', time()).' 00:00:00');
                $end_time   = strtotime(date('Y-m-d', $start_time + (3600 * 24 * 365)).' 00:00:00');
                $order_result   = $order
                    ->save([
                        'pay_time'  => strtotime($message['time_end']),
                        'pay_money' => $message['cash_fee'],
                        'pay_no'    => $message['transaction_id'],
                        'pay_type'  => 1,
                        'is_pay'    => 2,
                        'start_time'=> $start_time,
                        'end_time'  => $end_time
                    ], ['order_no' => $order_info->order_no]);
                if ($order_result && $member_result) {
                    $member->commit();
                    Distribution::agentUpgrade($order_info->order_no, $member_info->uid);
                    return true;
                }
                $member->rollback();
                return $fail['fail'];
            }
        });
        return $response;
    }
    /**
     * @purpose 微信支付异步回调
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function wechatAsync ()
    {
        $app        = Facade::payment('official_account');
        $response   = $app->handlePaidNotify(function($message, $fail) {
            $return_code    = strtolower($message['return_code']);
            $result_code    = strtolower($message['result_code']);
            if (
                $return_code === 'success' &&
                $result_code === 'success'
            ) {
                $order      = new \app\model\Order();
                $member     = new \app\model\Member();
                $order->startTrans();
                $uuid       = $message['attach'];
                $uid        = $member
                    ->where('uuid', $uuid)
                    ->value('uid');
                if (!$uid) {
                    $fail('Member not exists!');
                }
                $pay_voucher    = $message['out_trade_no'];
                $order_info     = $order
                    ->where([
                        'pay_voucher'  => $pay_voucher,
                        'uid'       => $uid
                    ])
                    ->lock(true)
                    ->field('id,uid,status,order_no,pay_voucher')
                    ->find();
                if (!$order_info) {
                    return $fail('Order not exists!');
                }
                if ($order_info->status !== 1) {
                    return $fail('Order status is error!');
                }
                $update_data                = [];
                $update_data['status']      = 2;
                $update_data['pay_time']    = strtotime($message['time_end']);
                $update_data['pay_money']   = $message['cash_fee'];
                $update_data['pay_no']      = $message['transaction_id'];
                $update_data['pay_type']    = 1;
                $order_process  = new OrderProcess();
                // 更新订单状态
                $order_result   = $order
                    ->isUpdate(true)
                    ->save($update_data, ['id' => $order_info->id]);
                // 记录订单流程
                $order_process_result =
                    $order_process
                        ->isUpdate(false)
                        ->data([
                            'order_id'      => $order_info->id,
                            'status'        => 2,
                            'operator_id'   => $order_info->uid,
                            'operator_type' => 1,
                            'description'   => '订单支付成功'
                        ])
                        ->save();
                if ($order_result && $order_process_result) {
                    $order->commit();
                    \app\mall\logic\Pay::distribution($order_info->order_no);
                    return true;
                }
                $order->rollback();
                return $fail('System fail!');
            }
        });
        return $response;
    }
}